/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.analyze.analysis;

import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.community.component.dialog.MessageDialog;
import cn.ac.nercis.pes.community.component.dialog.MessageType;
import cn.ac.nercis.pes.community.component.spreadsheet.analyze.RiskAnalysisSheetView;
import cn.ac.nercis.pes.community.constant.AppConstants;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.evaluation.analyze.RiskAnalysisController;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.evaluation.RiskAnalysisViewMapper;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.model.vo.evaluation.UnitRiskAnalysisVO;
import cn.ac.nercis.pes.community.utils.ControlUtils;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.analyze.RiskAnalysisView;
import cn.ac.nercis.pes.service.evaluation.UnitRiskAnalysisService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

/**
 * 风险分析列表管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class RiskAnalysisListController implements Initializable, GlobalEventHandle {

    @FXML
    private StackPane page;
    @FXML
    private VBox riskAnalysisBox;
    @FXML
    private AnchorPane emptyPane;
    @FXML
    private ImageView emptyImageView;
    @FXML
    private Label emptyLabel;
    @FXML
    private Label titleLbl;

    @FXML
    private Button tmpSaveButton;
    @FXML
    private Button saveButton;

    @FXML
    private RiskAnalysisSheetView sheetView;

    private final UnitRiskAnalysisService unitRiskAnalysisService;
    private final ExecutorService executor;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);

    private MenuVO currentLayerTarget;
    private String currentSystemId;

    public RiskAnalysisListController() {
        this.unitRiskAnalysisService = SpringUtils.getBean(UnitRiskAnalysisService.class);
        this.executor = SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        ControlUtils.initEmptyImageView(this.emptyImageView,log);
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerSheetChange(this.sheetView);
    }

    public void initializeData(String systemId,MenuVO layerTarget){
        LogUtils.info(log, "初始化风险分析列表信息...");
        this.currentSystemId = systemId;
        this.currentLayerTarget = layerTarget;
        ControlUtils.setLabelTextByLimit(titleLbl,currentLayerTarget.getTitle(),
                AppConstants.MAX_SHOW_TEXT_LENGTH);
        this.queryRiskAnalysis();
        this.sheetView.initialize(this::onOptionClick);
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        batchSaveRiskAnalysis(false,false);
    }

    @FXML
    public void onTmpSave(){
        LogUtils.info(log, "执行暂存操作...");
        this.batchSaveRiskAnalysis(false,false);
    }

    @FXML
    public void onFinishSave() {
        LogUtils.info(log, "执行保存操作...");
        this.batchSaveRiskAnalysis(false,true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        this.batchSaveRiskAnalysis(true,false);
    }

    private void batchSaveRiskAnalysis(boolean realTime,boolean finish){
        if(!this.sheetView.validate()){
            if(!realTime){
                AppUtils.showMessageDialog("以下标出的风险分析的必填信息不能为空",MessageType.WARN,this.page);
            }
            return;
        }
        var modifyData = this.sheetView.getModifyData().stream()
                .map(RiskAnalysisViewMapper.INSTANCE::toDTO)
                .toList();
        if (!realTime && CollectionUtils.isEmpty(modifyData)) {
            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
            refreshFinishProcess(finish);
            return;
        }
        LogUtils.info(log, "批量保存风险分析信息...");
        LogUtils.record(log, "请求数据，systemId：{},data:{}", this.currentSystemId, modifyData);
        //未保存的数据进行批量保存
        CompletableFuture.supplyAsync(() -> this.unitRiskAnalysisService.batchSaveRiskAnalysis(modifyData),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        //更新表数据
                        this.queryRiskAnalysis();
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                        refreshFinishProcess(finish);
                    } else {
                        if(realTime){
                            log.error("即时保存风险分析信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("批量保存风险分析信息出错!", ex);
                    return null;
                });
    }

    private void refreshFinishProcess(boolean finish){
        FinishState state = finish ? FinishState.FINISH : FinishState.INCOMPLETE;
        var riskView = AppStore.getEvaluationView(this.currentSystemId, RiskAnalysisView.class);
        if(riskView.getController() instanceof RiskAnalysisController controller){
            controller.setLayerFinishState(this.currentLayerTarget,state);
        }
    }

    public void onOptionClick(UnitRiskAnalysisVO riskAnalysis){
        LogUtils.info(log, "执行转到资产对象风险页面操作...");
        var riskView = AppStore.getEvaluationView(this.currentSystemId, RiskAnalysisView.class);
        if(riskView.getController() instanceof RiskAnalysisController controller){
            var data = sheetView.getRiskAnalysisList().stream().map(RiskAnalysisViewMapper.INSTANCE::toDTO).toList();
            controller.gotoAssetRiskAnalysis(RiskAnalysisViewMapper.INSTANCE.toDTO(riskAnalysis), data);
        }
    }

    private void queryRiskAnalysis() {
        LogUtils.info(log, "获取风险分析列表信息...");
        LogUtils.record(log, "请求数据，systemId：{},targetId:{}", this.currentSystemId, currentLayerTarget.getCode());
        CompletableFuture.supplyAsync(() -> this.unitRiskAnalysisService.findRiskAnalysis(this.currentSystemId,
                        currentLayerTarget.getCode()),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess() && CollectionUtils.isNotEmpty(res.getData())) {
                        this.riskAnalysisBox.setVisible(true);
                        this.emptyPane.setVisible(false);
                        var sheetData = res.getData().stream().map(RiskAnalysisViewMapper.INSTANCE::toVO).toList();
                        this.sheetView.loadContent(sheetData);
                    } else if (res.isSuccess()) {
                        this.riskAnalysisBox.setVisible(false);
                        this.emptyPane.setVisible(true);
                        this.emptyLabel.setText("风险分析列表为空");
                    } else {
                        this.riskAnalysisBox.setVisible(false);
                        this.emptyPane.setVisible(true);
                        this.emptyLabel.setText(res.getMsg());
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("获取风险分析列表信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL).withMessage("加载风险分析列表内容失败！")
                            .build().show();
                    return null;
                });
    }

}